package com.itheima.auth.handle;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.support.Result;
import com.itheima.utils.JwtTokenUtil;
import lombok.val;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

        UserDetails userDetails=(UserDetails) authentication.getPrincipal();

        try {
            //对密码进行加密
            String token = JwtTokenUtil.createToken(userDetails.getUsername());
            Result<String>result=Result.build(token);
            ObjectMapper objectMapper=new ObjectMapper();
            httpServletResponse.getWriter().write(objectMapper.writeValueAsString(result));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
